package com.hou.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author shkstart
 * @create 2021-09-09-21:40
 */
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    @Qualifier("stringRedisTemplate")
    private StringRedisTemplate redis;

    // redis自增
    @Override
    public int saveUserCount(Integer userId, Integer stockId) {
        // 设置redis变量名
        String save = "LIMIT"+userId+"_"+stockId;
        // 初始化访问次数
        int limit = -1;
        // 获取redis存储值
        String limitNum = redis.opsForValue().get(save);
        // 第一次访问时创建reids对象
        if (limitNum == null) {
            redis.opsForValue().set(save,"0",60, TimeUnit.SECONDS);
        } else {
            // 每次访问值加一
            limit = Integer.parseInt(limitNum) + 1;
            redis.opsForValue().set(save,String.valueOf(limit),60,TimeUnit.SECONDS);
        }
        return limit;
    }

    // 获取访问次数
    @Override
    public Boolean isBeyond(Integer userId, Integer stockId) {
        String save = "LIMIT"+userId+"_"+stockId;
        String limit = redis.opsForValue().get(save);
        if (Integer.parseInt(limit) <= 9) {
            return true;
        }
        else {
            return false;
        }
    }
}
